/*
 * Copyright 2009 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * 
 * Created with help of a tutorial from www.anddev.org
 */

package com.yannickstucki.android.musicqueue;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * A file browser. Used to set the music folder.
 * 
 * @author Yannick Stucki
 * 
 */
public class FolderScreen extends ListActivity {

  /**
   * Delay in milliseconds before displaying new list. Browsing feels more
   * "natural" this way.
   */
  private static final int BROWSING_DELAY = 10;

  /**
   * All the entries in the current directory.
   */
  private ArrayList<String> directoryEntries = new ArrayList<String>();

  /**
   * The directory in which the user currently is looking into.
   */
  private File currentDirectory;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    // setContentView() gets called within the next line,
    // so we do not need it here.
    browseToRoot();
  }

  /**
   * This function browses to the root-directory of the file-system.
   */
  private void browseToRoot() {
    browseTo(new File("/sdcard"));
  }

  /**
   * This function browses up one level according to the field:
   * currentDirectory.
   */
  private void upOneLevel() {
    if (this.currentDirectory.getParent().equals("/")) {
      finish();
    } else {
      this.browseTo(this.currentDirectory.getParentFile());
    }
  }

  /**
   * Set the view to a specific directory.
   */
  private void browseTo(final File directory) {
    if (directory.isDirectory()) {
      this.currentDirectory = directory;
      fill(directory.listFiles());
    }
  }

  /**
   * Fills the view with new files.
   */
  private void fill(File[] files) {
    this.directoryEntries.clear();

    // Add the "." and the ".." == 'Up one level'
    try {
      Thread.sleep(BROWSING_DELAY);
    } catch (InterruptedException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    this.directoryEntries.add(".");

    if (!this.currentDirectory.getParent().equals("/")) {
      this.directoryEntries.add("..");
    }

    // On relative Mode, we have to add the current-path to the
    // beginning
    int currentPathStringLenght = this.currentDirectory.getAbsolutePath()
        .length();
    for (File file : files) {
      String path = file.getPath();
      if (path.contains("/.")) {
        continue;
      }
      this.directoryEntries.add(file.getAbsolutePath().substring(
          currentPathStringLenght + 1));
    }

    ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
        R.layout.file_row, this.directoryEntries);

    this.setListAdapter(directoryList);
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    String selectedFileString = this.directoryEntries.get(position);
    if (selectedFileString.equals(".")) {
      Intent data = getIntent();
      data.putExtra(this.getString(R.string.folder_path_key), currentDirectory.toString());
      setResult(Activity.RESULT_OK, data);
      finish();
    } else if (selectedFileString.equals("..")) {
      this.upOneLevel();
    } else {
      File clickedFile = null;

      clickedFile = new File(this.currentDirectory.getAbsolutePath() + "/"
          + this.directoryEntries.get(position));

      if (clickedFile != null) {
        this.browseTo(clickedFile);
      }
    }
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      this.upOneLevel();
      return true;
    } else {
      return false;
    }
  }
}
